package com.mlt.back.web.filter;


import javax.servlet.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 判断是否登录过滤器
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //获取传来的请求
        String uri = request.getRequestURI();
        // 对请求的字符串进行截取 例如http://localhost:8080/aaa/bbb.jsp中我们想要的请求字符串为bbb.jsp
        uri = uri.substring(uri.lastIndexOf("/")+1);
        HttpSession session = request.getSession(false);
        if ((session!=null&&session.getAttribute("user")!=null)||uri.equals("login.jsp") ||uri.equals("managerLogin") ||uri.indexOf(".jpg") > 0 || uri.indexOf(".jpeg") > 0 || uri.indexOf(".png") > 0
                || uri.indexOf(".gif") > 0 || uri.indexOf(".css") > 0
                || uri.indexOf("js") > 0 || uri.indexOf(".bmp") > 0 ||uri.equals("code")){
            System.out.println("过滤请求路径：/"+uri);
            chain.doFilter(request,response);
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
